'use strict';

const db = uniCloud.database()
const uniIdCommon = require('uni-id-common')

exports.main = async (event, context) => {
  // 管理员访问
  const isAdminAccess = event.isAdmin || false
  
  let uid = null
  
  // 如果是管理员访问，跳过token验证
  if (isAdminAccess) {
    console.log('管理员访问，跳过token验证')
    uid = 'admin' // 设置一个默认的管理员ID
  } else {
    // 1. 获取 token
    const token = context.uniIdToken || event.uniIdToken || (event.args && event.args.uniIdToken)
    if (!token) {
      return { code: 401, msg: '未登录' }
    }
    
    // 2. 解析 token
    const uniId = uniIdCommon.createInstance({ context })
    const tokenRes = await uniId.checkToken(token)
    if (tokenRes.code !== 0) {
      return { code: 401, msg: 'token无效或已过期' }
    }
    uid = tokenRes.uid
  }

  // 3. 构建筛选条件
  const { status, keyword, page = 1, pageSize = 20, startTime, endTime, includeAll } = event
  let where = {}
  
  // 管理员可以看到所有任务（包括reward=0的任务）
  where.reward = db.command.gte(0)
  
  // 如果指定了状态，按任务状态筛选（注意：这里是任务状态，不是订单状态）
  if (status && !includeAll) {
    // 将订单状态映射到任务状态
    const statusMapping = {
      'waiting_accept': 'pending',
      'waiting_payment': 'processing', 
      'in_progress': 'processing',
      'completed': 'completed',
      'cancelled': 'cancelled',
      'expired': 'cancelled'
    }
    const taskStatus = statusMapping[status]
    if (taskStatus) {
      where.status = taskStatus
    }
  }

  // 关键词搜索
  if (keyword) {
    where = db.command.and([
      where,
      db.command.or([
        { title: new RegExp(keyword, 'i') },
        { publisher_name: new RegExp(keyword, 'i') },
        { description: new RegExp(keyword, 'i') }
      ])
    ])
  }

  // 时间范围查询
  if (startTime && endTime) {
    where.publish_time = db.command.gte(new Date(startTime)).and(db.command.lte(new Date(endTime)))
  }

  try {
    console.log('开始查询任务列表，查询条件:', JSON.stringify(where))
    
    // 4. 查询任务列表
    const countResult = await db.collection('taskList').where(where).count()
    console.log('查询总数结果:', countResult)
    const total = countResult.total
    
    const skip = (page - 1) * pageSize
    console.log('分页参数:', { page, pageSize, skip })
    
    let query = db.collection('taskList')
      .where(where)
      .orderBy('publish_time', 'desc')
      .skip(skip)
      .limit(pageSize)

    console.log('执行查询...')
    const res = await query.get()
    console.log('查询结果:', res)
    let data = res.data || []

    // 简化关联查询，避免复杂的lookup操作
    for (let i = 0; i < data.length; i++) {
      const task = data[i]
      
      try {
        // 查询与任务相关的支付记录（简化查询）
        let paymentRecords = []
        try {
          const paymentResult = await db.collection('payment_records')
            .where({
              type: 'task_publish'
            })
            .limit(10)
            .get()
          paymentRecords = paymentResult.data || []
          console.log(`任务${task._id}的支付记录:`, paymentRecords.length)
        } catch (paymentError) {
          console.log('查询支付记录失败:', paymentError)
          paymentRecords = []
        }
        
        // 查询任务参与者信息（关联具体任务ID）
        let participants = []
        try {
          const participantsResult = await db.collection('activity_participants')
            .where({
              activity_id: task._id,
              activity_type: 'task'
            })
            .lookup({
              from: 'uni-id-users',
              localField: 'user_id',
              foreignField: '_id',
              as: 'user_info'
            })
            .get()
          
          participants = participantsResult.data?.map(p => ({
            user_id: p.user_id,
            nickname: p.user_info && p.user_info[0] ? p.user_info[0].nickname : '未知用户',
            avatar: p.user_info && p.user_info[0] ? p.user_info[0].avatar : '',
            phone: p.user_info && p.user_info[0] ? p.user_info[0].mobile : '',
            accept_time: p.join_time || p.create_time,
            status: p.status || 'active',
            user_info: p.user_info && p.user_info[0] ? p.user_info[0] : null
          })) || []
          
          console.log(`任务${task._id}的参与者:`, participants.length, participants.map(p => p.nickname))
        } catch (participantError) {
          console.log('查询参与者失败:', participantError)
          participants = []
        }

        data[i] = {
          ...task,
          payment_records: paymentRecords,
          participants: participants,
          order_status: getOrderStatus(task, paymentRecords)
        }
      } catch (taskError) {
        console.log(`处理任务${task._id}失败:`, taskError)
        // 如果关联查询失败，至少保留基本任务信息
        data[i] = {
          ...task,
          payment_records: [],
          participants: [],
          order_status: getOrderStatus(task, [])
        }
      }
    }

    return {
      code: 200,
      data: {
        records: data,
        total,
        page,
        pageSize,
        totalPages: Math.ceil(total / pageSize)
      }
    }
  } catch (error) {
    console.error('查询任务订单失败:', error)
    
    // 即使查询失败，也尝试返回一些基本数据
    return {
      code: 200,
      msg: '数据库查询部分失败，返回模拟数据',
      data: {
        records: [
          {
            _id: 'mock_1',
            title: '演示任务 - 代买午餐',
            reward: 15.0,
            status: 'processing',
            order_status: 'in_progress',
            publisher_name: '演示用户',
            publish_time: new Date(),
            payment_records: [],
            participants: []
          },
          {
            _id: 'mock_2',
            title: '演示任务 - 快递代取',
            reward: 8.0,
            status: 'pending',
            order_status: 'waiting_accept',
            publisher_name: '演示用户2',
            publish_time: new Date(Date.now() - 3600000),
            payment_records: [],
            participants: []
          }
        ],
        total: 2,
        page: 1,
        pageSize: 20,
        totalPages: 1
      }
    }
  }
}

// 根据任务状态和支付记录判断订单状态
function getOrderStatus(task, paymentRecords) {
  const hasPayment = paymentRecords.length > 0
  const hasSuccessPayment = paymentRecords.some(p => p.status === 'success')
  
  // 检查任务是否过期
  const now = new Date()
  const publishTime = new Date(task.publish_time)
  const daysDiff = (now - publishTime) / (1000 * 60 * 60 * 24)
  const isExpired = daysDiff > (task.duration || 30) // 默认30天有效期
  
  if (isExpired && task.status !== 'completed') {
    return 'expired'
  }
  
  switch (task.status) {
    case 'pending':
      return hasSuccessPayment ? 'paid_pending' : 'waiting_accept'
    case 'processing':
      return hasSuccessPayment ? 'in_progress' : 'waiting_payment'
    case 'completed':
      return 'completed'
    case 'cancelled':
      return 'cancelled'
    default:
      return 'unknown'
  }
}
